import jsonpath
from jsonpath_ng import Index, Fields
from jsonpath_ng.ext import parse
from common.logger import GetLogger

def extract_json(json_object,json_path,index=0):
    '''
    :param json_object: 提取数据对象
    :param json_path: jsonpath表达式
    :param index: 1 默认0,提取第一个数据,2 如果想拿到第几个传数字索引,3 如果匹配所有 -1
    :return:
    '''
    logger=GetLogger.get_logger()
    res = jsonpath.jsonpath(json_object,json_path)
    # res如果提取到了 值是一个列表，没有匹配到是False
    if res:
        if index < 0:
            # 如果index<0 认为你想要匹配所有的结果
            return res
        else:
            # 如果index不小于0,那么你传几，就代表你匹配某一个
            return res[index]
    else:
        logger.exception(f'通过{json_path}没有提取到值')

def update_value_to_json(json_object,json_path,new_value):
    '''

    :param json_object: 替换目标整体数据 就是接口入参默认数据
    :param json_path: 目标字段对应的jsonpath表达式
    :param new_value: 目标字段对应的数据,缺参：设计 new_value值$del代表你要删除目标字段
    :return:
    '''
    # 将jsonpath表达式转换jsonpath对象
    jsonpath_expr = parse(json_path)
    # 通过jsonpath匹配目标数据 返回列表
    matches=jsonpath_expr.find(json_object)
    for match in matches:
        # 获取当前匹配对象的路径
        path=match.path
        # 判断是不是索引对象路径
        if isinstance(path,Index):
            if new_value == '$del':
                del match.context.value[match.path.index]
            else:
                print(f'{json_path}匹配到索引对象')
                # 完成数据替换
                match.context.value[match.path.index] = new_value
        # 判断是一个字段对象
        elif isinstance(path,Fields):
            if new_value == '$del':
                del match.context.value[match.path.fields[0]]
            else:
                print(f'{json_path}匹配到字段对象')
                match.context.value[match.path.fields[0]] = new_value
    return json_object

if __name__ == '__main__':

    aaa = {
    "code": 200,
    "msg": "操作成功",
    "data": {
        "records": [
            {
                "deleteFlag": 0,
                "createTime": "2024-04-02 18:11:21",
                "createUser": "1769548245587955714",
                "updateTime": "2024-04-26 11:10:36",
                "updateUser": "1769548245587955714",
                "dataSources": None,
                "allowModify": True,
                "tenantId": "-1",
                "id": "1775103719401979906",
                "customerCode": "客户06",
                "customerName": "淀粉肠",
                "contactName": "哈哈哈哈哈哈哈",
                "contactNumber": "15515705965",
                "contactAddress": "荆防颗粒打撒荆防颗粒",
                "mainBusinessDirection": "[]",
                "scaleSize": "",
                "remark": "范德萨发顺丰",
                "extJson": ""
            },
            {
                "deleteFlag": 0,
                "createTime": None,
                "createUser": None,
                "updateTime": "2024-04-24 16:58:16",
                "updateUser": None,
                "dataSources": None,
                "allowModify": True,
                "tenantId": "-1",
                "id": "1111",
                "customerCode": "22",
                "customerName": "2",
                "contactName": "2",
                "contactNumber": "2",
                "contactAddress": "2",
                "mainBusinessDirection": None,
                "scaleSize": None,
                "remark": "eeee",
                "extJson": None
            },
        ],
        "total": 7,
        "size": 10,
        "current": 1,
        "orders": [],
        "optimizeCountSql": True,
        "searchCount": True,
        "maxLimit": None,
        "countId": None,
        "pages": 1
    }
}
    # print(update_value_to_json(aaa, '$.goods_name', ''))
    # print(update_value_to_json(aaa, '$.goods_name', '$del'))
    # print(update_value_to_json(aaa, '$.goods_gallery_list[0]', '12312'))

    print()